<template>
    <div class="vue-uploader">
        <div class="file-list">
            <!--file-item-->
            <section v-if="status == 'ready'" class=" selectItem">
                <div class="title">图片</div>
                <div @click="add" class="add">
                    <!--<span>+</span>-->
                    <i class="icon-file"></i>
                </div>
            </section>
            <section v-for="(file, index) of localIds" class="file-item draggable-item">
                <img @click="previewPhoto(index)"  :src="file" alt="" ondragstart="return false;">
                <!--<p class="file-name">{{file.name}}</p>-->
                <span class="file-remove" @click.stop="remove(index)">+</span>
            </section>

        </div>

        <!--<section v-if="files.length != 0" class="upload-func">
            <div class="progress-bar">
                <section v-if="uploading" :width="(percent * 100) + '%'">{{(percent * 100) + '%'}}</section>
            </div>
            <div class="operation-box">
                <button v-if="status == 'ready'" @click="submit">上传</button>
                <button v-if="status == 'finished'" @click="finished">完成</button>
            </div>
        </section>-->
        <!-- <input type="file" class="input" :disabled="disabled" accept="image/*" @change="fileChanged" ref="file" multiple="multiple"> -->
    </div>
</template>
<script>
    import Vue from "vue";
    import { Toast} from "mint-ui";
    export default {
        props: {
            src: {
                type: String,
                required: true
            },
            disabled:{
            }
        },
        data() {
            return {
                status: 'ready',
                files: [],
                point: {},
                uploading: false,
                percent: 0,
                localIds:'',
                imgs:null,
                resUpload:[],
            }
        },
        methods: {

            uploadImages (index) {
                let xIndex = index || 0
                console.log(xIndex,'xIndex');
                console.log(this.imgs,'this.imgsX');
                if (xIndex > this.imgs.length-1) {
                    console.log(this.imgs,'this.imgs');
                    this.$emit('update:uploadRes',this.resUpload);
                    return;
                }
                // 加载图片
                wx.uploadImage({
                    localId: this.imgs[xIndex].toString(),
                    success: (res) => {
                        console.log(res,'res');
                        let localData = res.serverId
                        console.log(localData,'localData');
                        this.resUpload.push(localData)
                        this.uploadImages(xIndex + 1);
                        console.log(this.resUpload,'this.resUpload');

                    },
                    fail: function (res) {
                        Toast({
                            message: "上传图片失败，请重新选择",
                            position: "center",
                            className: "toastStyle",
                            duration: 1000
                        });

                    }
                })
            },            
            add() {
                console.log('add');
                console.log(wx.chooseImage,'wx.chooseImage');
                var self= this;
                wx.chooseImage({
                    count: 9, // 默认9
                    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                    success: function (res) {
                        var localIds = res.localIds; // 返回选定照片的本地ID列表，
                        console.log(localIds,'localIds');

                        self.imgs = localIds;

                       
                        // localIds.forEach((val)=>{
                        //     console.log(val,'val');
         
                        //     var imgCanvas = new Image(); 
                        //     imgCanvas.crossOrigin = '*'; 
                        //     imgCanvas.src = val; 
                        //     imgCanvas.onload=function(){
                        //         console.log('onload');
                        //         var canvas = document.createElement("canvas");
                        //         //获取绘画上下文
                        //         ctx = canvas.getContext("2d");
 
                        //         // 获取图片宽高
                        //         var imgWidth = imgCanvas.width;
                        //         var imgHeight = imgCanvas.height;
                
                        //         //设置画布宽高与图片宽高相同
                        //         canvas.width = imgWidth;
                        //         canvas.height = imgHeight;
                
                        //         //绘制图片
                        //         ctx.drawImage(imgCanvas,0,0);
                        //         //图片展示的 data URI
                        //         var imageData = canvas.toDataURL('image/jpeg');
                        //         self.localIds.push(imageData);
                        //         console.log(self.localIds,'self.localIds');
                        //     }
                            
                        // })

                        

                        // localIds.forEach((val)=>{
                        //     wx.getLocalImgData({
                        //         localId: val, // 图片的localID
                        //         success: function (res) {
                        //             var localData = res.localData; // localData是图片的base64数据，可以用img标签显示
                        //             self.localIds.push(localData);
                        //         }
                        //     });
                        // })
                        if (self.isIos()) {
                            localIds.forEach((val)=>{
                                wx.getLocalImgData({
                                    localId: val, // 图片的localID
                                    success: function (res) {
                                        var localData = res.localData; // localData是图片的base64数据，可以用img标签显示
                                        self.localIds.push(localData);
                                    }
                                });
                            })
                        } else {
                            self.localIds = localIds;
                        }

                        console.log(self.localIds,'self.localIds');
                        
                        self.$emit('input',localIds);

                        self.uploadImages();
                        
                        // andriod中localId可以作为img标签的src属性显示图片；
                        // 而在IOS中需通过上面的接口getLocalImgData获取图片base64数据，从而用于img标签的显示
                    
                    }
                });

                // this.$refs.file.click()
            },
            isIos:function(){
                var u = navigator.userAgent, app = navigator.appVersion; 
                var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
                return isiOS;
            },
            submit() {
                if (this.files.length === 0) {
                    console.warn('no file!');
                    return
                }
                const formData = new FormData()
                this.files.forEach((item) => {
                    formData.append(item.name, item.file)
                })
                const xhr = new XMLHttpRequest()
                xhr.upload.addEventListener('progress', this.uploadProgress, false)
                xhr.open('POST', this.src, true)
                this.uploading = true
                xhr.send(formData)
                xhr.onload = () => {
                    this.uploading = false
                    if (xhr.status === 200 || xhr.status === 304) {
                        this.status = 'finished'
                        console.log('upload success!')
                    } else {
                        console.log(`error：error code ${xhr.status}`)
                    }
                }
            },
            finished() {
                this.localIds = []
                this.status = 'ready'
            },
            remove(index) {
                this.localIds.splice(index, 1);
                this.resUpload.splice(index, 1);
                this.$emit('update:uploadRes',this.resUpload);
            },
            previewPhoto:function(index){
                wx.previewImage({
                    current: this.localIds[index], // 当前显示的图片链接
                    urls: this.localIds
                });
                // this.$emit('previewPhoto',index)
            },
            fileChanged() {
                const list = this.$refs.file.files
                console.log(list);
                for (let i = 0; i < list.length; i++) {
                    if (!this.isContain(list[i])) {
                        const item = {
                            name: list[i].name,
                            size: list[i].size,
                            file: list[i]
                        }
                        this.html5Reader(list[i], item)
                        this.files.push(item)
                    }
                }
                this.$emit('input',this.files);
                // this.$refs.file.value = ''
            },
            // 将图片文件转成BASE64格式
            html5Reader(file, item){
                const reader = new FileReader()
                reader.onload = (e) => {
                    this.$set(item, 'src', e.target.result)
                }
                reader.readAsDataURL(file);
                console.log(this.files);
            },
            isContain(file) {
                this.files.forEach((item) => {
                    if(item.name === file.name && item.size === file.size) {
                        return true
                    }
                })
                return false
            },
            uploadProgress(evt) {
                const component = this
                if (evt.lengthComputable) {
                    const percentComplete = Math.round((evt.loaded * 100) / evt.total)
                    component.percent = percentComplete / 100
                } else {
                    console.warn('upload progress unable to compute')
                }
            }
        }
    }
</script>
<style>
.vue-uploader {
    /*border: 1px solid #e5e5e5;*/
    position: relative;
    width:100%;
}
.vue-uploader .file-list {
    padding:  0 0.3rem;
}
.vue-uploader .file-list:after {
    content: '';
    display: block;
    clear: both;
    visibility: hidden;
    line-height: 0;
    height: 0;
    font-size: 0;
}
.vue-uploader .file-list .file-item {
    float: left;
    position: relative;
    margin-right: 0.2rem;
    width: 80px;
    text-align: center;
}
.vue-uploader .file-list .file-item img{
    width: 80px;
    height: 80px;
    border: 1px solid #ececec;
}
.vue-uploader .file-list .file-item .file-remove {
    position: absolute;
    right: -0.10rem;
    /* display: none; */
    display: inline;
    top: -0.10rem;
    width: 0.28rem;
    height: 0.28rem;
    color: white;
    cursor: pointer;
    line-height: 0.28rem;
    border-radius: 100%;
    -webkit-transform: rotate(45deg);
    transform: rotate(45deg);
    background: rgba(255, 0, 0, 0.9);
}
/*.vue-uploader .file-list .file-item:hover .file-remove {
    display: inline;
}*/
.selectItem >div{
    /*display:flex;*/
    display: inline-block;
}

.selectItem{
    line-height:0.8rem;
}
.input{
    width:0.8rem;
    height:0.8rem;
    border:none;
    outline:none;
    opacity:0;
    position: absolute;
    top:0;
    right:0;
    z-index:1000;
}
.vue-uploader .file-list .file-item .file-name {
    margin: 0;
    height: 40px;
    word-break: break-all;
    font-size: 14px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}
/*.vue-uploader .add {
    width: 80px;
    height: 80px;
    margin-left: 10px;
    float: left;
    text-align: center;
    line-height: 80px;
    border: 1px dashed #ececec;
    font-size: 30px;
    cursor: pointer;
}*/
.vue-uploader .add {
    /* width: 0.4rem; */
    /* height: 0.4rem; */
    margin-left: 10px;
    /* float: left; */
     /*margin-right: 0.2rem; */
    float: right;
    /* text-align: center; */
    /* line-height: 0.4rem; */
    /* border: 1px dashed #ececec; */
    font-size: 0.32rem;
    cursor: pointer;
}
.vue-uploader .upload-func {
    display: flex;
    padding: 10px;
    margin: 0px;
    background: #f8f8f8;
    border-top: 1px solid #ececec;
}
.vue-uploader .upload-func .progress-bar {
    flex-grow: 1;
}
.vue-uploader .upload-func .progress-bar section {
    margin-top: 5px;
    background: #00b4aa;
    border-radius: 3px;
    text-align: center; 
    color: #fff;
    font-size: 12px;
    transition: all .5s ease;
}
.vue-uploader .upload-func .operation-box {
    flex-grow: 0;
    padding-left: 10px;
}
.vue-uploader .upload-func .operation-box button {
    padding: 4px 12px;
    color: #fff;
    background: #007ACC;
    border: none;
    border-radius: 2px;
    cursor: pointer;
}
/*.vue-uploader > input[type="file"] {
    display: none;
}*/
.vue-uploader>input[type="file"]{
      width:0.8rem;
      height:0.8rem;
      border:none;
      outline:none;
      opacity:0;
      float:right;
    }
</style>